import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { LoginDto } from 'src/app/dto/login.dto';
import { LoginService } from 'src/app/services/login/login.service';
import { LocalStorageService } from 'src/app/services/local-storage/local-storage.service';
import { Router } from '@angular/router';
import { CourseService } from 'src/app/services/course/course.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  validateForm: FormGroup;

  constructor(
    private formBuilder: FormBuilder,
    public router: Router,
    private loginService: LoginService,
    private courseService: CourseService,
    private localStorage: LocalStorageService
  ) {
    this.validateForm = this.formBuilder.group({
      no: ['100000006', [Validators.required]],
      pw: ['Pw100000006', [Validators.required]]
    });
  }

  ngOnInit() {}

  onSubmit(loginDto: LoginDto) {
    for (const i in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(i)) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    }

    this.loginService.getToken(loginDto).subscribe(
      data => {
        this.courseService.token = data.token;
        this.localStorage.set('token', data.token);
        this.router.navigateByUrl('/');
      },
      error => {
        console.error(error);
      }
    );
  }
}
